package com.guducat.collegeWeb.config;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义错误控制器
 * 确保所有错误都返回JSON格式响应，而不是HTML页面
 */
@RestController
public class ApiOnlyErrorController implements ErrorController {

    @RequestMapping("/error")
    public ResponseEntity<Map<String, Object>> handleError(HttpServletRequest request) {
        Map<String, Object> errorResponse = new HashMap<>();
        
        // 获取错误状态码
        Integer statusCode = (Integer) request.getAttribute("jakarta.servlet.error.status_code");
        String requestUri = (String) request.getAttribute("jakarta.servlet.error.request_uri");
        String errorMessage = (String) request.getAttribute("jakarta.servlet.error.message");
        
        if (statusCode == null) {
            statusCode = 500;
        }
        
        // 构建错误响应
        errorResponse.put("code", statusCode);
        errorResponse.put("timestamp", System.currentTimeMillis());
        errorResponse.put("path", requestUri != null ? requestUri : "unknown");
        
        // 根据不同的错误状态码返回不同的消息
        switch (statusCode) {
            case 404:
                if (requestUri != null && requestUri.startsWith("/api/")) {
                    errorResponse.put("msg", "API接口不存在");
                    errorResponse.put("error", "API Not Found");
                } else {
                    errorResponse.put("msg", "这是纯API服务，请访问前端应用");
                    errorResponse.put("error", "Static Resource Not Supported");
                    errorResponse.put("frontend_urls", Map.of(
                        "pc", "请访问独立的PC前端应用",
                        "mobile", "请访问独立的移动端应用"
                    ));
                }
                break;
            case 405:
                errorResponse.put("msg", "请求方法不被允许");
                errorResponse.put("error", "Method Not Allowed");
                break;
            case 500:
                errorResponse.put("msg", "服务器内部错误");
                errorResponse.put("error", "Internal Server Error");
                break;
            default:
                errorResponse.put("msg", errorMessage != null ? errorMessage : "请求处理失败");
                errorResponse.put("error", "Request Failed");
        }
        
        errorResponse.put("data", null);
        
        // 输出错误日志用于调试
        System.out.println("=== API错误处理 ===");
        System.out.println("状态码: " + statusCode);
        System.out.println("请求路径: " + requestUri);
        System.out.println("错误信息: " + errorMessage);
        System.out.println("==================");
        
        return ResponseEntity.status(HttpStatus.valueOf(statusCode)).body(errorResponse);
    }
}
